/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controle;

import dao.Dao;
import entidades.Categoria;
import entidades.Noticia;
import entidades.Upload;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Maria Eloyza
 */
public class NoticiaServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet NoticiaServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet NoticiaServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String op = request.getParameter("op");
        int id = Integer.parseInt(request.getParameter("id"));
        Dao<Noticia> daoN = new Dao<Noticia>(Noticia.class);
        HttpSession session = request.getSession(true);
        if (op.equals("Ver")) {
            Noticia noticia = daoN.get(id);
            session.setAttribute("noticia", noticia);

            response.sendRedirect("visualizarNoticia.jsp");
        }
        if (op.equals("Remover")) {
            daoN.remove(id);
            
            request.setAttribute("noticias", daoN.list());
            response.sendRedirect("noticia.jsp");
        }

        if (op.equals("Editar")) {
            Noticia noticia = daoN.get(id);
            session.setAttribute("noticia", noticia);

            response.sendRedirect("editarNoticia.jsp");
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    public final String dir = "/files/";
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //Cria um objeto upload já setando e criando o diretorio que os
        // arquivos serão armazenados
        Upload upload = new Upload(getServletContext().getRealPath(dir));

        // Retorna um list com todos os componentes de uma requisição
        List list = upload.processRequest(request);

        // Neste Map você obteve todos os campos do formulário.
        Map<String, String> map = upload.getFormValues(list);
        
        String titulo = map.get("titulo");
        
        int categoria = Integer.parseInt(map.get("categoriaNoticia"));
        
        String conteudo = map.get("conteudo");
        String op = map.get("op");
        ArrayList<String> lista = new ArrayList<String>();
        lista.add(map.get("imagem1"));
        lista.add(map.get("imagem2"));
        lista.add(map.get("imagem3"));
        lista.add(map.get("imagem4"));
        lista.add(map.get("imagem5"));
        Dao<Noticia> daoN = new Dao<Noticia>(Noticia.class);
        Dao<Categoria> daoC = new Dao<Categoria>(Categoria.class);

        if (op.equals("Inserir")) {


            // DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            Date date = new Date();
            // dateFormat.format(date);

            Noticia n = new Noticia();

            n.setCategoria(daoC.get(categoria));
            n.setDataNoticia(date);
            n.setFotos(lista);
            n.setTexto(conteudo);
            n.setTitulo(titulo);
            //n.setUsuario(null); =====> FALTA ISSO AQUI <=====
            
            daoN.insert(n);
            
            List<Noticia> listaNoticia = daoN.list();
            request.setAttribute("noticias", listaNoticia);
        }
        
        if (op.equals("Buscar")){  
            if (titulo == null) {
                titulo = "";
            }   
            
            List<Noticia> listaNoticia = daoN.listByTituloAndCategoria(titulo, categoria);
            request.setAttribute("noticias", listaNoticia);
            request.setAttribute("buscou", true);
        }
       
        response.sendRedirect("noticia.jsp");
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
